using M13.Base;
using M13.Game.World;
using M13.GameSystem;
using M13.Math;
using M13.Utility;
using QFramework;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using M13.DataStructure;
using Test;
using UnityEditor;
using UnityEngine;
using static UnityEngine.GraphicsBuffer;

#if UNITY_EDITOR

namespace M13
{
    public class DebugChunkData : MonoBehaviour, IController
    {
        public Vector2Int chunkLocalCoord;
        SaveConfig _saveConfig;
        ISaveSystem _saveSystem;

        private void Start()
        {
            _saveConfig = this.GetModel<IGameModal>().GameSaveConfig.Value;
            _saveSystem = this.GetSystem<ISaveSystem>();
        }
        public void DebugChunk()
        {
            Region region = RegionDataParser.RegionDecompress(_saveSystem, _saveConfig, M13Mathf.ChunkToRegionCoord(chunkLocalCoord));
            byte[] chunkSingularCompressedData = null;
            int offset = M13Mathf.ChunkIndexOnRegion(chunkLocalCoord);
            ChunkDataBoot chunkDataBoot = region.ChunkDataBoots[offset];
            region.RegionDataArray.DynamicExpansionArray.GetArrays(out chunkSingularCompressedData, chunkDataBoot.dataOffset, chunkDataBoot.GetTotalLength(), true);
            //Debug.LogError($"���飺{chunkLocalCoord},������{chunkDataBoot.dataOffset}, �ܳ��ȣ�{chunkSingularCompressedData.Length}, �����ݣ�{Application.dataPath + "TestText.txt"}");
            Debug.LogError($"�ܳ��ȣ�{region.RegionDataArray.DynamicExpansionArray.Array.Length}������λ�ã�{Application.dataPath + "/TestText.txt"}");
            AddTxtTextByFileStream(BytesToHexString.ToHexStringStringBuilder(region.RegionDataArray.DynamicExpansionArray.Array));
        }

        public void AddTxtTextByFileStream(string txtText)
        {
            string path = Application.dataPath + "/TestText.txt";
            // �ļ�������һ���ı��ļ�
            FileStream file = new FileStream(path, FileMode.Create);
            //�õ��ַ�����UTF8 ������
            byte[] bts = System.Text.Encoding.UTF8.GetBytes(txtText);
            // �ļ�д��������
            file.Write(bts, 0, bts.Length);
            if (file != null)
            {
                //��ջ���
                file.Flush();
                // �ر���
                file.Close();
                //������Դ
                file.Dispose();
            }
        }

        public IArchitecture GetArchitecture()
        {
            return GameArchitecture.Interface;
        }
    }

    [CustomEditor(typeof(DebugChunkData))]
    public class GUIOnClass : Editor
    {
        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();
            DebugChunkData mapTextureCreate = (DebugChunkData)target;
            if (GUILayout.Button("��ȡ��������"))
            {
                mapTextureCreate.DebugChunk();
            }

        }
    }
}

#endif